package com.chenhb.watermarkutils;

import java.io.*;
import java.util.Date;

import com.chenhb.watermarkutils.bo.WatermarkBo;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

/**
 * PDF添加图片水印工具
 *
 * @author 陈海波
 * @date 2021-04-21
 */
public class PdfImageWatermarkUtil extends AbstractWatermark {

    /**
     * @throws DocumentException
     * @throws IOException
     */
    public static ByteArrayOutputStream mark(WatermarkBo watermarkBo)
            throws DocumentException, IOException {
        // 要输出的pdf文件
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfReader reader = new PdfReader(new FileInputStream(watermarkBo.getResourceFile()));
        // 获取文档高度
        Rectangle pageSize = reader.getPageSize(1);
        float height = pageSize.getHeight();
        PdfStamper stamper = new PdfStamper(reader, bos);
        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;
        PdfGState gs = new PdfGState();
        for (int i = 1; i < total; i++) {
            // 在内容下方加水印
            content = stamper.getUnderContent(i);
            content.beginText();
            gs.setFillOpacity(watermarkBo.getTransparency());
            content.setGState(gs);
            Image image = Image.getInstance(filetoByte(watermarkBo.getWatermarkImageFile()));
            // 设置图片水印位置
            float x = watermarkBo.getHeight() / 1.875f;
            float y = watermarkBo.getHeight() / 1.875f;
            image.setAbsolutePosition(watermarkBo.getOffsetX(), height - y - watermarkBo.getOffsetY());
            image.scaleAbsoluteHeight(y);
            image.scaleAbsoluteWidth(x);
            // 设置旋转角度
            image.setRotation(watermarkBo.getDegree());
            content.addImage(image);
            content.endText();
        }
        stamper.close();
        return bos;
    }

}
